package com.xxl.util;

import com.xxl.dto.UserDto;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 发放令牌和解密令牌
 * 发放token的工具类
 * @author xxl
 * @date 2023/4/2
 */
@Component
@Slf4j

public class JwtUtil {
    /**
     * 发放令牌
     */
    public static String getToken(Object data,long time) {
        JwtBuilder builder = Jwts.builder();
        builder
                //设置头部信息
                .setHeaderParam("type", "jwt")
                .setHeaderParam("alg", "HS256")
                //设置载体
                .claim(ConstantField.USER_INFO,data)
                //设置过期时间
                .setExpiration(new Date(System.currentTimeMillis()+time))
                //拼接头和载体
                //整体加密
                .signWith(SignatureAlgorithm.HS256, ModelData.JWT_KEY);
        return builder.compact();
    }

    /**
     * 解密令牌
     */
    public static Object parseJwt(String token) {
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(ModelData.JWT_KEY).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        log.info("令牌的过期时间为"+body.getExpiration());
        return body.get(ConstantField.USER_INFO);
    }

    @Resource
    HttpServletRequest request;
    /**
     * 返回token
     */
    public String getToken() {
        if (ModelData.USER_TOKEN == null) {
            List<Cookie> cookies = Arrays.stream(request.getCookies()).filter(ck -> ck.getName().equals(ConstantField.USER_COOKIE_NAME)).toList();
            if (cookies.size() > 0 && !cookies.get(0).getValue().isEmpty()) {
                return cookies.get(0).getValue();
            }
        }
        return ModelData.USER_TOKEN;
    }

    /**
     * 返回token中存的值
     * 只返回用户名和密码
     */
    public UserDto getTokenUser() {
        UserDto userDto = new UserDto();
        if (JwtUtil.parseJwt(getToken()) instanceof HashMap<?,?> map) {
            userDto.setUsername((String) map.get("username"));
            userDto.setPassword((String) map.get("password"));
        }
        return userDto;
    }
}
